import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2025-03-13
 * Time: 22:36
 */
public class Main {
    public static int minOperations1(int[] nums, int x) {
        int n = nums.length;
        int target = 0;
        for (int i = 0; i < n; i++) {
            target += nums[i];
        }
        target -= x;
        if(target < 0){
            return -1;
        }
        if (target == 0) return n;
        int len  = -1;
        int sum = 0;
        int left = 0;
        int right = 0;
        while (right < n){
            sum += nums[right];
            while (sum>target && left < right){
                sum -= nums[left];
                left++;
            }
            if (sum == target){
                len = Math.max(len,right-left+1);
            }
            right++;
        }

        if(len == -1){
            return len;
        }else {
            return n-len;
        }

    }

    public static int minOperations(int[] nums,int x){
        int sum = 0;
        for (int a: nums) {
            sum += a;
        }
        int target = sum - x;
        //处理细节
        if(target < 0){
            return -1;
        }
        int ret = -1;
        for (int left = 0,right = 0,tmp = 0;  right < nums.length ; right++) {
            tmp += nums[right]; //进窗口
            while (tmp > target){//判断
                tmp -= nums[left++];//出窗口
            }
            if(tmp == target){
                ret = Math.max(ret,right - left + 1);//更新结果
            }
        }
        if(ret == -1){
            return ret;
        }else {
            return nums.length-ret;
        }

    }
    public static void main(String[] args) {
        int[] nums = {8828,9581,49,9818,9974,9869,9991,10000,10000,10000,9999,9993,9904,8819,1231,6309};
        int x = 134365;
        System.out.println(minOperations(nums, x)); // 输出：16
    }
}
